package com.dure.hotmemory.adapters;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dure.commonlib.util.AssetsUtil;
import com.dure.commonlib.util.DbUtils;
import com.dure.commonlib.util.FileUtils;
import com.dure.commonlib.util.StreamUtil;
import com.dure.commonlib.util.ToastUtils;
import com.dure.hotmemory.MainActivity;
import com.dure.hotmemory.R;
import com.dure.hotmemory.bean.Code;
import com.dure.hotmemory.bean.CodeDao;
import com.dure.hotmemory.listeners.SelectPictureListener;
import com.dure.hotmemory.utils.DialogUtil;
import com.dure.hotmemory.utils.ShowSelectPictureDialogUtil;
import com.socks.library.KLog;

import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dure on 2017/5/31.
 */

public class CodeEditAdapter extends RecyclerView.Adapter<CodeEditAdapter.MyViewHolder> {
    List<Code> codeList = new ArrayList<>();
    Context context;
    MainActivity activity;
    Code currentEditCode;

    public CodeEditAdapter(Context context) {
        this.context = context;
        activity = (MainActivity) context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.edit_code_item, parent,
                false));
        return holder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        final Code code = codeList.get(position);
        holder.nameET.setText(code.name);
        holder.numberTV.setText(code.number);
        holder.nameET.setBackgroundColor(Color.TRANSPARENT);

        if (!TextUtils.isEmpty(code.image)) {
            Bitmap bitmap = null;
            if (!code.isCreated) {
                bitmap = BitmapFactory.decodeStream(AssetsUtil.getAssets(context, code.image));
            } else {
                FileInputStream is = null;
                try {
                    is = new FileInputStream(code.image);
                    bitmap = BitmapFactory.decodeFileDescriptor(is.getFD(), null, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap != null)
                holder.codeIV.setImageBitmap(bitmap);

        } else {
            holder.codeIV.setImageResource(R.mipmap.add);
        }

        if (code.isCreated) {
            holder.editTV.setVisibility(View.VISIBLE);
            if (code.changeable) {
                holder.editTV.setText("完成");
                holder.deleteTV.setVisibility(View.VISIBLE);
                holder.nameET.setEnabled(true);
                holder.nameET.setBackgroundResource(R.drawable.transparent_arc_stroke_drawable);
            } else {
                holder.editTV.setText("编辑");
                holder.deleteTV.setVisibility(View.GONE);
                holder.nameET.setEnabled(false);
                holder.nameET.setBackgroundColor(Color.TRANSPARENT);
            }
        } else {
            holder.editTV.setVisibility(View.GONE);
        }

        holder.editTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (code.changeable) {
                    String newName = holder.nameET.getText().toString();
                    if (TextUtils.isEmpty(newName)) {
                        ToastUtils.show(context, "内容不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(code.image)) {
                        ToastUtils.show(context, "请指定图片");
                        return;
                    }
                    code.name = newName;
                    addOrUpdateItemToDB(code);
                }
                code.changeable = !code.changeable;
                notifyItemChanged(position);


            }
        });

        holder.deleteTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteItem(code);
            }
        });

        holder.codeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (code.changeable) {
                    code.name = holder.nameET.getText().toString();
                    currentEditCode = code;
                    DialogUtil.imagePickerDialog(activity, new SelectPictureListener() {
                        @Override
                        public void takePhoto() {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                            String fileRootDir = activity.getFilesDir().getAbsolutePath();
                            String fileRootDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                            String savaFilePath = fileRootDir + "/temp.jpg";
                            if (FileUtils.createFile(savaFilePath)) {// 文件创建成功
                                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(new File(fileRootDir, "temp.jpg")));
                                activity.startActivityForResult(intent, SelectPictureListener.PHOTO_GRAPH);
                            }
                        }

                        @Override
                        public void takePhotoAlbum() {
                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    IMAGE_UNSPECIFIED);
                            activity.startActivityForResult(intent, PHOTO_ZOOM);
                        }
                    });
                }
            }
        });
    }

    private void deleteItem(Code code) {
        CodeDao codeDao = activity.daoSession.getCodeDao();
        if (code.position == 0) {
            Code secondCode = codeList.get(1);
            secondCode.position = 0;
            codeDao.update(secondCode);
        }

        int itemIndex = this.codeList.indexOf(code);
        this.codeList.remove(code);
        notifyItemRemoved(itemIndex);

        if (codeDao.hasKey(code))
            codeDao.delete(code);
    }

    private void addOrUpdateItemToDB(Code code) {

        CodeDao codeDao = activity.daoSession.getCodeDao();
        if (code.position != -1) {
            codeDao.update(code);
        } else {
            Code lastCode = codeList.get(codeList.size() - 2);
            int lastPosition = lastCode.position;
            code.position = lastPosition + 1;
            code.type = lastCode.type;

            codeDao.insert(code);
        }
    }

    public Code getCurrentEditCode() {
        return currentEditCode;
    }

    @Override
    public int getItemCount() {
        return codeList.size();
    }

    public void setCodeList(List<Code> codeList) {
        if (codeList != null && codeList.size() > 0) {
            this.codeList.addAll(codeList);
            notifyDataSetChanged();
        }
    }

    public void addCodeItem(Code code) {
        this.codeList.add(code);
        notifyDataSetChanged();
    }

    public List<Code> getCodeList() {
        return codeList;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        TextView numberTV, deleteTV, editTV;
        EditText nameET;
        ImageView codeIV;

        public MyViewHolder(View view) {
            super(view);
            nameET = (EditText) view.findViewById(R.id.name_et);
            numberTV = (TextView) view.findViewById(R.id.number_tv);
            deleteTV = (TextView) view.findViewById(R.id.delete_tv);
            editTV = (TextView) view.findViewById(R.id.edit_tv);
            codeIV = (ImageView) view.findViewById(R.id.code_iv);
        }
    }
}
